import type { RadioChangeEvent, UploadProps } from 'antd';
import { Upload } from 'antd';
import { message } from 'antd';
import { Button, Card, Form, Input, Radio, Select } from 'antd';
import { useRef, useState } from 'react';
import styles from '../index.less';
import registerStyles from './index.less';
import './custom.less';
import { history } from 'umi';
// import { getFakeCaptcha } from "@/services/ant-design-pro/login";
import { ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import { USER_Signup, USER_requestVerifyCode, USER_OrganList, USER_SubjectList } from '@/graphql';
import type { VerifyCode } from '../Login/index';
import { useMutation, useQuery } from 'react-apollo';
import { ButtonStyle, captchaStyle } from '../../../../config/globalStyle';
import classNames from 'classnames';
import { ApolloError } from 'apollo-client/errors/ApolloError';
import { userRequestUploadURL, userSaveUploadLog } from '@/graphql/mutations';
import client from '@/graphql/client';
import SparkMD5 from 'spark-md5';
import { request } from 'umi';

//  有个bug 变量的border进不去 以后研究一下为什么
// const customRadio = {
//   display: 'inline-block',
//   background: 'white',
//   marginRight: '8px',
//   borderRadius: '12px',
//   border: '1px solid #d9d9d',
// };

function ConfirmPasswordValidator(rule, value, callback, source, options) {
  const { getFieldValue } = options.form;
  console.log(getFieldValue('ProFormTextPassword'));
  if (getFieldValue('ProFormTextPassword') !== value) {
    callback('两次密码输入不一致');
  } else {
    callback();
  }
}

const Register = () => {
  const [form] = Form.useForm();
  const formRef = useRef<any>(null);
  const form2Ref = useRef<any>(null);
  const [sexValue, setSexValue] = useState('MALE');
  const [nameValue, setNameValue] = useState('');
  const [phoneValue, setPhoneValue] = useState('');
  const [verifyCode, setVerifyCode] = useState('');
  const [password, setPassword] = useState('');
  const [subjectValue, setSubjectValue] = useState('');
  const [stepValue, setStepValue] = useState('first');
  const [schoolValue, setSchoolValue] = useState('');
  const [identityValue, setIdentityValue] = useState('TEACHER'); // STUDENT / TEACHER / PARENT
  const [requestVerifyCode] = useMutation(USER_requestVerifyCode);
  const [requestUserSignup, requestUserSignupResult] = useMutation(USER_Signup);

  const organListData = useQuery(USER_OrganList, {
    variables: {
      type: 'Organ',
    },
  });

  const subjectListData = useQuery(USER_SubjectList, {
    variables: {
      type: 'Subject',
      organ_id: schoolValue,
    },
  });

  const toOrganOption = (param: any) => {
    console.log(param);
    if (param.loading) return [];
    const res = param.data.nodeList.map((item: { id: string; name: string }) => {
      const { id, name } = item;
      return { value: id, label: name };
    });
    return res;
  };

  const handleVerifyCode: VerifyCode = async (phone: string) => {
    const params = {
      variables: { input: { phone } },
    };
    try {
      const VerifyCode = await requestVerifyCode(params);
      console.log('result', VerifyCode);
      if (VerifyCode === false) {
        return;
      }
      message.success('获取验证码成功！');
      return VerifyCode;
    } catch (errors) {
      console.log(errors);
      return message.error('该手机号已有注册用户，请更换手机号！');
    }
  };
  const onFirstStepFinish = (values: any) => {
    console.log('Success:', values);
    formRef.current
      .validateFields()
      .then(() => {
        // 遍历所有表单项，判断是否填写完毕
        const hasError = Object.keys(formRef.current.getFieldsError()).some((field) => {
          return formRef.current.isFieldTouched(field) && formRef.current.getFieldError(field);
        });
        if (hasError) {
          // 表单验证失败，展示错误信息
        } else {
          // 表单验证成功，可以提交表单
          setStepValue('second');
        }
      })
      .catch((errors: any) => {
        // 表单验证失败，展示错误信息
        console.log(errors);
      });
  };

  const onFinish = async () => {
    const baseParams = {
      name: nameValue,
      phone: phoneValue,
      sex: sexValue,
      verifyCode,
      password,
      organ_id: schoolValue,
      signupType: identityValue,
    };
    const studentParams = {
      ...baseParams,
    };
    const teacherParams = {
      ...baseParams,
      subject_id: subjectValue,
    };
    const parentParams = {
      ...baseParams,
    };
    const paramsType = (type: string) => {
      switch (type) {
        case 'STUDENT':
          return studentParams;
        case 'TEACHER':
          return teacherParams;
        case 'PARENT':
          return parentParams;
        default:
          return baseParams;
      }
    };
    const paramsData = paramsType(identityValue);
    console.log('onFinish', paramsData);
    // return
    try {
      const res = await requestUserSignup({
        variables: {
          input: paramsData,
        },
      });
      console.log(res);
      return;
    } catch (error) {
      const err = (requestUserSignupResult?.error?.networkError as any)?.result?.errors[0].message;
      message.error(err);
      return;
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setNameValue(e.target.value);
  };
  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setPhoneValue(e.target.value);
  };
  const handleVerifyCodeChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    console.log(e);
    setVerifyCode(e.target.value);
  };
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setPassword(e.target.value);
  };
  const handleSubjectChange = (value: string) => {
    setSubjectValue(value);
  };
  const handleSexChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setSexValue(e.target.value);
  };
  const handleSchoolChange = (value: string) => {
    console.log(`selected ${value}`);
    setSchoolValue(value);
  };
  const handleIdentityChange = (e: RadioChangeEvent) => {
    console.log(`radio checked:${e.target.value}`);
    setIdentityValue(e.target.value);
  };
  const upoloadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload: (file): any => {
      console.log(file);
      const fileReader = new FileReader();
      fileReader.readAsArrayBuffer(file);

      const spark = new SparkMD5.ArrayBuffer();
      fileReader.onload = (e) => {
        spark.append(e.target.result);
        const md5 = spark.end();

        const formData = new FormData();
        formData.append('file', file);
        client
          .mutate({
            mutation: userRequestUploadURL,
            variables: {
              input: {
                filename: file.name,
                size: file.size,
                md5,
              },
            },
          })
          .then(async (res) => {
            console.log(res);
            const { signed_url, mime_type, object_key, url } = res.data.userRequestUploadURL;
            console.log(signed_url);
            try {
              // request('www.baidu.com', {
              //   method: 'put',
              // });
              const data = await request(`/ossapi${signed_url.split('com')[1]}`, {
                method: 'PUT',
                mode: 'cors',
                responseType: 'blob',
                credentials: 'include',
                headers: {
                  'Content-Type': 'application/octet-stream',
                  'Access-Control-Allow-Origin': '*',
                },
                // data: formData,
              });
              console.log(data);
              client.mutate({
                mutation: userSaveUploadLog,
                variables: {
                  input: {
                    size: file.size,
                    md5,
                    object_key,
                    mime_type,
                    url,
                  },
                },
              });
            } catch (error) {
              console.log(error);
            }

            console.log(formData);
          });
      };
      return false;
    },
  };

  return (
    <div className={classNames(styles.container, styles.registerContainer)}>
      <div className={styles.registerHeader}>
        <img alt="logo" src="/logo.png" />
        <div>95Waltz-Ai</div>
      </div>
      <div className={styles.content}>
        <Card style={{ borderRadius: '15px' }}>
          <div className={registerStyles.title}>用户注册</div>
          {stepValue === 'first' && (
            <Form
              className={registerStyles.form}
              labelCol={{ span: 6 }}
              ref={formRef}
              onFinishFailed={onFinishFailed}
              style={{ maxWidth: 300 }}
              requiredMark={false} // 不显示* 但是仍然需要require
            >
              {/* <Form.Item name="avatar" rules={[{ required: true, message: '请输上传头像' }]}> */}
              <div className="avatarContainer">
                {/* <div className={styles.avatar}> */}
                <div className="avatar">
                  {/* <img src={require('../../../../public/avatar.png')} alt="" /> */}
                </div>
                <Upload {...upoloadProps}>
                  <Button type="primary" style={ButtonStyle}>
                    上传头像
                  </Button>
                </Upload>
              </div>
              {/* </Form.Item> */}
              <Form.Item
                name="rigisterUsername"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input value={nameValue} onChange={handleNameChange} />
              </Form.Item>
              <Form.Item
                name="sex"
                label="性别"
                rules={[{ required: true, message: '请选择性别' }]}
              >
                <Radio.Group onChange={handleSexChange} value={sexValue}>
                  <Radio value="MALE">男</Radio>
                  <Radio value="FEMALE">女</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  {
                    pattern: /^1\d{10}$/,
                    message: '不合法的手机号！',
                  },
                ]}
              >
                <Input placeholder="请输入手机号" value={phoneValue} onChange={handlePhoneChange} />
              </Form.Item>
              <Form.Item
                name="school"
                label="学校"
                rules={[{ required: true, message: '请选择学校' }]}
              >
                <Select
                  style={{ width: 120 }}
                  placeholder="请选择学校"
                  onChange={handleSchoolChange}
                  options={toOrganOption(organListData)}
                />
              </Form.Item>
              <Form.Item
                name="identity"
                label="身份"
                rules={[{ required: true, message: '请选择身份' }]}
              >
                <Radio.Group onChange={handleIdentityChange} defaultValue="a">
                  <Radio.Button className="customRadio" value="TEACHER">
                    老师
                  </Radio.Button>
                  <Radio.Button className="customRadio" value="PARENT">
                    家长
                  </Radio.Button>
                  <Radio.Button className="customRadio" value="STUDENT">
                    学生
                  </Radio.Button>
                </Radio.Group>
              </Form.Item>
              {identityValue === 'PARENT' && (
                <>
                  <Form.Item
                    name="studentName"
                    label="学生姓名"
                    rules={[{ required: true, message: '请输入学生姓名' }]}
                  >
                    <Input placeholder="请输入学生姓名" />
                  </Form.Item>
                  {/* <Form.Item
                    name="relation"
                    label="与学生关系"
                    rules={[{ required: true, message: '请输入与学生关系' }]}
                  >
                    <Input placeholder="请输入与学生关系" />
                  </Form.Item> */}
                </>
              )}
              {identityValue === 'TEACHER' && (
                <Form.Item
                  name="subject"
                  label="学科"
                  rules={[{ required: true, message: '请输入学科' }]}
                >
                  <Select
                    style={{ width: 120 }}
                    placeholder="请选择学科"
                    onChange={handleSubjectChange}
                    options={toOrganOption(subjectListData)}
                  />
                </Form.Item>
              )}
              <Form.Item>
                <div className={registerStyles.buttonGroup}>
                  <Button onClick={() => history.push('/user/login')} style={ButtonStyle}>
                    取消
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={onFirstStepFinish}
                    style={ButtonStyle}
                  >
                    下一步
                  </Button>
                </div>
              </Form.Item>
            </Form>
          )}
          {stepValue === 'second' && (
            <Form
              className="registerform2"
              labelCol={{ span: 6 }}
              ref={form2Ref}
              form={form}
              // onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              style={{ maxWidth: 300 }}
              requiredMark={false}
            >
              <Form.Item
                name="secondStepPhone"
                label="手机号"
                // rules={[{ required: true, message: "请输入手机号" }]}
              >
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined className={styles.prefixIcon} />,
                  }}
                  name="mobile"
                  placeholder={'请输入手机号！'}
                  rules={[
                    {
                      required: true,
                      message: '手机号是必填项！',
                    },
                    {
                      pattern: /^1\d{10}$/,
                      message: '不合法的手机号！',
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item
                name="secondStepCaptcha"
                label="验证码"
                // rules={[{ required: true, message: "请输入验证码" }]}
              >
                <ProFormCaptcha
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  value={verifyCode}
                  onChange={handleVerifyCodeChange}
                  captchaProps={{
                    size: 'large',
                    style: captchaStyle,
                  }}
                  placeholder={'请输入验证码！'}
                  captchaTextRender={(timing: any, count: any) => {
                    if (timing) {
                      return `${count} ${'秒后重新获取'}`;
                    }
                    return '获取验证码';
                  }}
                  phoneName="mobile"
                  name="captcha"
                  rules={[
                    {
                      required: true,
                      message: '验证码是必填项！',
                    },
                  ]}
                  onGetCaptcha={async (phone) => handleVerifyCode(phone)}
                />
              </Form.Item>
              <Form.Item
                name="secondStepPassword"
                label="密码"
                // rules={[{ required: true, message: "请输入密码" }]}
              >
                <ProFormText.Password
                  name="ProFormTextPassword"
                  fieldProps={{
                    autoComplete: 'new-password',
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  onChange={handlePasswordChange}
                  placeholder={'请输入密码'}
                  rules={[
                    {
                      required: true,
                      message: '密码不少于8位, 并且必须包含两种字符',
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item
                name="againPassword"
                label="确认密码"
                // rules={[{ required: true, message: "请输入密码" }]}
              >
                <ProFormText.Password
                  name="againPassword"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请再次输入密码'}
                  rules={[
                    {
                      required: true,
                      message: '密码不少于8位, 并且必须包含两种字符',
                    },
                    {
                      validator: (rule, value, callback) =>
                        ConfirmPasswordValidator(rule, value, callback, form.getFieldsValue(), {
                          form,
                        }),
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item>
                <div className={registerStyles.buttonGroup}>
                  <Button onClick={() => setStepValue('first')} style={ButtonStyle}>
                    上一步
                  </Button>
                  <Button type="primary" htmlType="submit" onClick={onFinish} style={ButtonStyle}>
                    下一步
                  </Button>
                </div>
              </Form.Item>
            </Form>
          )}
        </Card>
      </div>
    </div>
  );
};

export default Register;
